<script setup>
import {
  roomMessageService,
  roomHeadFileService,
  insertRoomDataService,
  updataRoomDataService,
  delRoomService,
} from '@/api/room'
import { ref, onMounted, computed } from 'vue'
import { Edit, Delete, Plus } from '@element-plus/icons-vue'
import { formatTime } from '@/utils/format'
import axios from 'axios'
import { useRoomStore } from '@/stores'

const channelList = ref([]) //定义房间列表
const loading = ref(false) //loading
const dialogVisible = ref(false) // 弹窗是否显示
const total = ref(0) // 总条数
const id = ref(0) // 房间id
const roomStore = useRoomStore()
//获取房间列表信息
const title = ref('')
const getChannelList = async () => {
  loading.value = true
  const res = await roomMessageService()
  roomStore.setRoomMessage(res.data.data)
  channelList.value = roomStore.roomMessage
  total.value = res.data.data.length
  loading.value = false
}
// 一进页面就加载
onMounted(() => {
  getChannelList()
})
const form = ref() //绑定el-form标签
const roomMessage = ref({
  room_name: '',
  room_type: '',
  room_img: '',
  capacity: null,
})
const rules = {
  room_name: [{ required: true, message: '房间名称不能为空', trigger: 'blur' }],
  room_type: [{ required: true, message: '房间类型不能为空', trigger: 'blur' }],
  room_img: [{ required: true, message: '照片不能为空', trigger: 'blur' }],
  capacity: [
    {
      required: true,
      message: '容量不能为空',
      trigger: 'blur',
    },
    {
      type: 'number',
      message: '容量必须是数字',
      trigger: ['blur', 'change'],
      transform(value) {
        return Number(value)
      },
    },
  ],
}
const uploadRef = ref() //绑定图片上传upload标签
const imgUrl = ref([])
const fileList = ref([]) // 文件列表
let formData = new FormData()

/* 重新创建 FormData 实例：每次点击上传时，重新创建 formData，
确保每次上传时都是一个干净的 FormData 对象。
清空 fileList：在每次上传文件时清空 fileList，只保留
当前上传的文件，避免上次上传的文件影响后续操作。 */

const onUploadFile = (uploadFile) => {
  fileList.value = [uploadFile.raw]
  imgUrl.value = URL.createObjectURL(uploadFile.raw)
  console.log(uploadFile.raw, fileList.value)

  formData = new FormData()
  formData.append('file', fileList.value[0]) // 'file' 是后端接收字段名
}
const beforeUpload = async (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    alert('请上传图片文件')
  }
  return isImage // 只有图片文件会继续上传
}
// 添加分类
const onAddChannel = () => {
  title.value = '添加分类'
  roomMessage.value = {
    // 置空表单
    room_name: '',
    room_type: '',
    room_img: '',
    capacity: null,
  }
  imgUrl.value = '' //清空照片缓存
  selectedId.value = null //清空下拉菜单选定值
  dialogVisible.value = true
}
//下拉菜单的选项列表
const selectedId = ref(null)
const roomStyle = ref([
  { id: 1, label: '大床房' },
  { id: 2, label: '双床房' },
  { id: 3, label: '三床房' },
  { id: 4, label: '别墅' },
])
// 获取选中房间的名称
const getRoomName = (roomId) => {
  const room = roomStyle.value.find((r) => r.id === roomId)
  roomMessage.value.room_type = room.label
}

//提交表单
const confirm = async () => {
  if (roomMessage.value.room_type === '') {
    getRoomName(selectedId.value)
    const res = await roomHeadFileService(formData) // 上传文件数据
    roomMessage.value.room_img = res.data.fileUrl // 获取图片网络地址URL，并赋值给roomMessage.value.room_img
    await insertRoomDataService(roomMessage.value) // 插入一条rooms数据
  } else {
    if (roomMessage.value.room_type !== selectedId.value) {
      getRoomName(selectedId.value)
    }
    const res = await roomHeadFileService(formData) // 上传文件数据
    roomMessage.value.room_img = res.data.fileUrl // 获取图片网络地址URL，并赋值给roomMessage.value.room_img
    const updatedRoomMessage = { ...roomMessage.value, room_id: id.value }
    await updataRoomDataService(updatedRoomMessage)
    ElMessage({ type: 'success', message: '修改成功' })
    console.log(updatedRoomMessage)
    // 创建一个新的对象并添加 room_id 属性
    console.log(roomMessage.value)
  }
  getChannelList()
  dialogVisible.value = false
}
// 将网络图片地址转换为File对象
async function fetchImageAsFile(imageUrl, filename) {
  try {
    const response = await axios.get(imageUrl, { responseType: 'arraybuffer' })
    const imageData = response.data
    // 第二步：将图片数据转换为Blob对象
    const blob = new Blob([imageData], { type: response.headers['content-type'] })
    // 第三步：创建一个新的File对象
    // 创建File对象，文件名和MIME类型可以通过blob的类型推断出来
    const file = new File([blob], filename, { type: blob.type })

    return file
  } catch (error) {
    console.error('Error:', error)
    return null
  }
}
// 编辑房间列表信息
const onEditChannel = (row) => {
  title.value = '编辑分类'
  dialogVisible.value = true
  id.value = row.room_id
  roomMessage.value = {
    room_name: row.room_name,
    room_type: row.room_type,
    room_img: row.room_img,
    capacity: row.capacity,
  }
  selectedId.value = row.room_type
  const filename = row.room_img.match(/[^/]+$/)[0] // 使用正则表达式匹配最后一个斜杠后面的部分
  console.log(filename)
  imgUrl.value = fetchImageAsFile(row.room_img, filename)
    //Promise {<pending>} 是因为 Promise 可能还在执行中，
    // 并且它是一个异步操作的返回值。你看到的 [[PromiseState]]: "fulfilled"
    // 表示该 Promise 已经被解决，并且 [[PromiseResult]] 中包含了 File 对象。
    //方法 1：使用 .then() 来处理异步 Promise
    .then((file) => {
      if (file) {
        console.log('File object:', file)
        imgUrl.value = URL.createObjectURL(file)
      }
    })
    .catch((error) => console.error('Error in fetching image:', error))
  console.log(imgUrl.value)

  console.log(roomMessage.value)
}
/* 方法 2：使用 async/await 语法 */
/* async function handleImage() {
  try {
    const file = await fetchImageAsFile('http://hotel.ttt/room/Rooms/1.jpg', '1.jpg');
    console.log(file);  // 这里的 file 是 File 对象
    // 你可以在这里操作 file 对象
  } catch (error) {
    console.error('Error:', error);
  }
}

handleImage(); */
// 删除房间列表信息
const onDelChannel = async (row) => {
  console.log(row.room_id)
  await ElMessageBox.confirm('你确认删除该该条数据吗？', '温馨提示', {
    type: 'warning',
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  })
  await delRoomService(row.room_id)
  ElMessage({ type: 'success', message: '删除成功' })
  getChannelList()
}
//分页
const currentPage = ref(1) // 当前页
const pagesize = ref(3) // 每页条数
// pagesize每页条数 改变时触发
const onSizeChange = (size) => {
  currentPage.value = 1
  pagesize.value = size
  getChannelList()
}
// 分页数据计算属性
const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pagesize.value
  const end = start + pagesize.value
  return channelList.value.slice(start, end)
})

// currentPage 当前页 改变时触发
const onCurrentChange = (page) => {
  currentPage.value = page
  getChannelList()
}
</script>
<template>
  <page-container title="房间分类">
    <template #extra>
      <el-button type="primary" @click="onAddChannel">添加分类</el-button>
    </template>

    <div>
      <el-table :data="paginatedData" v-loading="loading" style="width: 100%; margin-top: 20px">
        <el-table-column label="房间ID" align="center" width="100">
          <template #default="{ $index }">
            <!-- 当前页的索引加上偏移量来计算序号 -->
            {{ $index + 1 + (currentPage - 1) * pagesize }}
          </template>
        </el-table-column>
        <el-table-column label="房间名称" prop="room_name" align="center"></el-table-column>
        <el-table-column label="房间类型" prop="room_type" align="center"></el-table-column>
        <!-- 图片列 -->
        <el-table-column label="房间图片" align="center">
          <template #default="{ row }">
            <img
              :src="row.room_img"
              alt="房间图片"
              style="width: 100px; height: 60px; object-fit: cover"
            />
          </template>
        </el-table-column>
        <el-table-column label="容量" prop="capacity" align="center"></el-table-column>
        <el-table-column label="创建时间" align="center">
          <template #default="{ row }">
            {{ formatTime(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100">
          <!-- row 就是 channelList 的一项，类似于item； $index 下标 -->
          <template #default="{ row }">
            <el-button
              :icon="Edit"
              circle
              plain
              type="primary"
              @click="onEditChannel(row)"
            ></el-button>
            <el-button
              :icon="Delete"
              circle
              plain
              type="danger"
              @click="onDelChannel(row)"
            ></el-button>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="没有数据"></el-empty>
        </template>
      </el-table>
      <el-dialog v-model="dialogVisible" :title="title" width="40%">
        <div>
          <el-form
            ref="form"
            style="max-width: 600px"
            :model="roomMessage"
            status-icon
            :rules="rules"
            label-width="auto"
            class="demo-ruleForm"
          >
            <el-form-item label="房间名称" prop="room_name">
              <el-input v-model="roomMessage.room_name" style="width: 350px" autocomplete="off" />
            </el-form-item>
            <el-form-item label="房间类型" prop="room_type">
              <template #default>
                <el-select v-model="selectedId" style="width: 350px" placeholder="请选择房间">
                  <el-option
                    v-for="item in roomStyle"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </template>
            </el-form-item>
            <el-form-item label="房间照片" prop="room_img">
              <template #default>
                <el-upload
                  ref="uploadRef"
                  class="avatar-uploader"
                  :auto-upload="false"
                  :show-file-list="false"
                  :on-change="onUploadFile"
                  :before-upload="beforeUpload"
                >
                  <img v-if="imgUrl" :src="imgUrl" class="avatar" />
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
              </template>
            </el-form-item>
            <el-form-item label="房间容量" prop="capacity">
              <el-input v-model.number="roomMessage.capacity" style="width: 350px" />
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="confirm"> 确认 </el-button>
          </span>
        </template>
      </el-dialog>
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pagesize"
        :page-sizes="[2, 3, 4, 5, 10]"
        layout="jumper, total, sizes, prev, pager, next"
        background
        :total="total"
        @size-change="onSizeChange"
        @current-change="onCurrentChange"
        style="margin-top: 20px; justify-content: flex-end"
      />
    </div>
  </page-container>
</template>
<style lang="scss" scoped>
.el-table {
  margin-top: 20px;
}
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
.example-showcase .el-dropdown + .el-dropdown {
  margin-left: 15px;
}
.example-showcase .el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}
</style>
